package models

import (
	"gorm.io/gorm"
	"gvb_server/global"
	"gvb_server/models/ctype"
	"os"
)

var NewBannerModel BannerModel = BannerModel{}

type BannerModel struct {
	Model
	Path      string          `gorm:"type:varchar(255);not null;comment:路径" json:"path"`
	Hash      string          `gorm:"type:varchar(255);not null;comment:hash" json:"hash"` // 用于判断重复图片
	Name      string          `gorm:"type:varchar(255);not null;comment:名称" json:"name"`
	ImageType ctype.ImageType `gorm:"default:1" json:"image_type"`
}

// BeforeDelete 根据图片的ImageType字段删除对应的资源
func (b *BannerModel) BeforeDelete(tx *gorm.DB) (err error) {
	global.DB.Find(&b)
	if b.ImageType == ctype.Local {
		err := os.Remove(b.Path)
		if err != nil {
			global.Log.Error("删除图片失败", err)
			return err
		}
		global.Log.Infof("删除本地图片: %s", b.Path)
	}
	return nil
}
